﻿using Microsoft.Win32;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;



namespace WPFByCoreApp
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class TestDataGridWindow : Window
    {
        #region 成员变量
        Key? CurKey;

        private List<Key> ControlKeys = new List<Key> { Key.Enter, Key.M };

        private List<Key> InputKeys = new List<Key> { Key.D0, Key.D1 };
        #endregion

        #region 构造函数
        public TestDataGridWindow()
        {
            InitializeComponent();

            this.DataContext = new MainViewModel();

            //this.dg1.PreviewKeyDown += dg1_PreviewKeyDown;
            //this.dg1.PreparingCellForEdit += dg1_PreparingCellForEdit;
            //this.dg1.BeginningEdit += dg1_BeginningEdit;
            //this.dg1.CellEditEnding += dg1_CellEditEnding;
            //this.dg1.RowEditEnding += dg1_RowEditEnding;
            //this.dg1.GotFocus += dg1_GotFocus;
            //this.dg1.MouseDoubleClick += Dg1_MouseDoubleClick;

            this.dg1.AddingNewItem += Dg1_AddingNewItem;
            this.dg1.InitializingNewItem += Dg1_InitializingNewItem;
        }

        private void Dg1_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
        {

            //this.dg1.Items.Add(CollectionView.NewItemPlaceholder);

            DataGridRow newItemPlaceholderRow = this.dg1.ContainerFromItem<DataGridRow>(CollectionView.NewItemPlaceholder);
            if (newItemPlaceholderRow != null)
            {
                newItemPlaceholderRow.Visibility = Visibility.Visible;
                newItemPlaceholderRow.CoerceValue(VisibilityProperty);
            }


        }

        private void Dg1_AddingNewItem(object sender, AddingNewItemEventArgs e)
        {

        }
        #endregion

        #region 窗体事件
        private void dg1_PreviewKeyDown(object sender, KeyEventArgs e)
        {

            CurKey = e.Key == Key.ImeProcessed ? e.ImeProcessedKey : e.Key;

            if (!CurKey.HasValue)
            {
                return;
            }

            Debug.WriteLine("dg1_PreviewKeyDown-----Key:" + CurKey + ";时间:" + DateTime.Now);




            if (ControlKeys.Contains(CurKey.Value) || InputKeys.Contains(CurKey.Value))
            {
                if (!dg1.IsEditing())
                {
                    dg1.BeginEdit();

                }

                if (ControlKeys.Contains(CurKey.Value) && !(Keyboard.IsKeyToggled(Key.LeftShift) || Keyboard.IsKeyToggled(Key.RightShift)))
                {
                    dg1.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(dg1), 0, Key.Tab) { RoutedEvent = Keyboard.KeyDownEvent });
                    dg1.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(dg1), 0, Key.Tab) { RoutedEvent = Keyboard.KeyUpEvent });

                    e.Handled = true;
                }
            }
        }

        private void dg1_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            //Debug.WriteLine("dg1_PreparingCellForEdit----时间:" + DateTime.Now);

            if (CurKey.HasValue)
            {
                MyVisualTreeHelper.FindVisualChild<TextBox>(e.EditingElement).ForEach(par =>
                {
                    #region 通过键盘key，转换得到键盘对应的字符串，给textbox赋值
                    //wpfKey = KeyInterop.KeyFromVirtualKey((int)formsKey);
                    //Keys formsKey = (Keys)KeyInterop.VirtualKeyFromKey(CurKey.Value);
                    //par.Text = KeyCharTool.KeyCodeToStr(formsKey); 
                    #endregion


                    #region 通过textbox获取焦点，将事件传到textbox，让系统自己给textbox赋值
                    par.Focus();
                    par.Select(0, par.Text.Length);
                    #endregion


                    #region 主动调用textbox的KeyDownEvent和KeyUpEvent事件，未达到给textbox赋值的效果
                    //par.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(par), 0, CurKey.Value) { RoutedEvent = Keyboard.KeyDownEvent });
                    //par.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(par), 0, CurKey.Value) { RoutedEvent = Keyboard.KeyUpEvent });
                    #endregion
                });

                #region 直接通过模拟键盘触发窗体的KeyDownEvent和KeyUpEvent事件，给textbox赋值
                //Keys formsKey = (Keys)KeyInterop.VirtualKeyFromKey(CurKey.Value);
                //byte b = ((byte)KeyCharTool.VkKeyScan(Convert.ToChar("-")));
                //KeyCharTool.keybd_event(b, 0, 0, 0);
                //KeyCharTool.keybd_event(b, 0, 0x02, 0);
                #endregion

                //CurKey = null;
            }
        }

        private void dg1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
        }

        private void dg1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
        }

        private void dg1_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
        }

        private void dg1_GotFocus(object sender, RoutedEventArgs e)
        {
        }

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            Debug.WriteLine("TextBox_PreviewKeyDown----时间:" + DateTime.Now);

        }

        private void btnBeginEdit_Click(object sender, RoutedEventArgs e)
        {
            //this.dg1.GetCell(0, 0)?.Focus();

            //this.dg1.BeginEdit();
        }

        private void btnCancelEdit_Click(object sender, RoutedEventArgs e)
        {
            this.dg1.CancelEdit();
        }

        private void btnAdd_OnClick(object sender, RoutedEventArgs e)
        {
            ((MainViewModel)this.DataContext).InsertCommand.Execute(null);
        }

        private void Dg1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
        }

        private void btnUIDump_Click(object sender, RoutedEventArgs e)
        {
            string a = null;
            a.PadLeft(10);
        }

        private void btnThreadDump_Click(object sender, RoutedEventArgs e)
        {
            ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(par =>
            {
                int i = 0;
                while (true)
                {
                    if (i == 10)
                    {
                        throw new Exception("thread");
                    }
                    i++;
                    Thread.Sleep(100);
                }
            }), null);
        }

        private void btnTaskDump_Click(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                int i = 0;
                while (true)
                {
                    if (i == 10)
                    {
                        throw new Exception("task");
                    }
                    i++;
                    Thread.Sleep(100);
                }
            });
        }
        #endregion


        string WaterState(int tempInFahrenheit) =>
            tempInFahrenheit switch
            {
                (> 32) and (< 212) => "liquid",
                < 32 => "solid",
                > 212 => "gas",
                32 => "solid/liquid transition",
                212 => "liquid / gas transition",
            };
    }

}

